package com.zenithmind.document.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.document.pojo.domain.DocumentShare;
import com.zenithmind.document.pojo.vo.DocumentShareVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 文档分享Mapper接口
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Mapper
public interface DocumentShareMapper extends BaseMapper<DocumentShare> {

    /**
     * 分页查询分享（包含关联信息）
     * 
     * @param page 分页参数
     * @param documentId 文档ID
     * @param sharerId 分享者ID
     * @param shareType 分享类型
     * @param status 状态
     * @return 分页结果
     */
    IPage<DocumentShareVO> selectSharePageWithDetails(Page<DocumentShareVO> page,
                                                     @Param("documentId") String documentId,
                                                     @Param("sharerId") String sharerId,
                                                     @Param("shareType") Integer shareType,
                                                     @Param("status") Integer status);

    /**
     * 根据分享码获取分享信息
     * 
     * @param shareCode 分享码
     * @return 分享信息
     */
    DocumentShareVO selectShareByCode(@Param("shareCode") String shareCode);

    /**
     * 获取文档分享列表
     * 
     * @param documentId 文档ID
     * @param includeExpired 是否包含过期的分享
     * @return 分享列表
     */
    @Select("SELECT s.*, d.title as document_title, u.real_name as sharer_name " +
            "FROM document_share s " +
            "LEFT JOIN document d ON s.document_id = d.id " +
            "LEFT JOIN user u ON s.sharer_id = u.id " +
            "WHERE s.document_id = #{documentId} AND s.deleted = 0 " +
            "AND (#{includeExpired} = true OR s.status != 2) " +
            "ORDER BY s.create_time DESC")
    List<DocumentShareVO> selectDocumentShares(@Param("documentId") String documentId,
                                              @Param("includeExpired") Boolean includeExpired);

    /**
     * 获取用户分享列表
     * 
     * @param sharerId 分享者ID
     * @param limit 限制数量
     * @return 分享列表
     */
    @Select("SELECT s.*, d.title as document_title, u.real_name as sharer_name " +
            "FROM document_share s " +
            "LEFT JOIN document d ON s.document_id = d.id " +
            "LEFT JOIN user u ON s.sharer_id = u.id " +
            "WHERE s.sharer_id = #{sharerId} AND s.deleted = 0 " +
            "ORDER BY s.create_time DESC " +
            "LIMIT #{limit}")
    List<DocumentShareVO> selectUserShares(@Param("sharerId") String sharerId,
                                          @Param("limit") Integer limit);

    /**
     * 检查分享码是否存在
     * 
     * @param shareCode 分享码
     * @param excludeId 排除的分享ID
     * @return 是否存在
     */
    @Select("SELECT COUNT(*) > 0 FROM document_share " +
            "WHERE share_code = #{shareCode} AND deleted = 0 " +
            "AND (#{excludeId} IS NULL OR id != #{excludeId})")
    Boolean checkShareCodeExists(@Param("shareCode") String shareCode,
                                 @Param("excludeId") String excludeId);

    /**
     * 验证分享访问权限
     * 
     * @param shareCode 分享码
     * @param password 密码
     * @return 是否有权限
     */
    Boolean validateShareAccess(@Param("shareCode") String shareCode,
                               @Param("password") String password);

    /**
     * 记录分享访问
     * 
     * @param shareId 分享ID
     * @param accessType 访问类型（view, download）
     * @param userId 用户ID
     * @param ipAddress IP地址
     * @param userAgent 用户代理
     * @return 影响行数
     */
    int recordShareAccess(@Param("shareId") String shareId,
                         @Param("accessType") String accessType,
                         @Param("userId") String userId,
                         @Param("ipAddress") String ipAddress,
                         @Param("userAgent") String userAgent);

    /**
     * 更新分享统计
     * 
     * @param shareId 分享ID
     * @param type 统计类型（access, download）
     * @return 影响行数
     */
    @Update("UPDATE document_share SET " +
            "access_count = CASE WHEN #{type} = 'access' THEN access_count + 1 ELSE access_count END, " +
            "download_count = CASE WHEN #{type} = 'download' THEN download_count + 1 ELSE download_count END, " +
            "last_access_time = CASE WHEN #{type} IN ('access', 'download') THEN NOW() ELSE last_access_time END, " +
            "update_time = NOW() " +
            "WHERE id = #{shareId}")
    int updateShareStatistics(@Param("shareId") String shareId, @Param("type") String type);

    /**
     * 生成唯一分享码
     * 
     * @return 分享码
     */
    String generateUniqueShareCode();

    /**
     * 批量更新过期分享状态
     * 
     * @param currentTime 当前时间
     * @return 影响行数
     */
    @Update("UPDATE document_share SET status = 2, update_time = NOW() " +
            "WHERE expire_time IS NOT NULL AND expire_time < #{currentTime} " +
            "AND status = 1 AND deleted = 0")
    int batchUpdateExpiredShares(@Param("currentTime") LocalDateTime currentTime);

    /**
     * 批量更新超限分享状态
     * 
     * @return 影响行数
     */
    @Update("UPDATE document_share SET status = 2, update_time = NOW() " +
            "WHERE max_access_count IS NOT NULL " +
            "AND access_count >= max_access_count " +
            "AND status = 1 AND deleted = 0")
    int batchUpdateOverLimitShares();

    /**
     * 获取分享统计信息
     * 
     * @param shareId 分享ID
     * @return 统计信息
     */
    DocumentShareVO selectShareStatistics(@Param("shareId") String shareId);

    /**
     * 获取热门分享
     * 
     * @param limit 限制数量
     * @return 分享列表
     */
    @Select("SELECT s.*, d.title as document_title, u.real_name as sharer_name " +
            "FROM document_share s " +
            "LEFT JOIN document d ON s.document_id = d.id " +
            "LEFT JOIN user u ON s.sharer_id = u.id " +
            "WHERE s.deleted = 0 AND s.status = 1 " +
            "AND s.share_type = 1 " +
            "ORDER BY s.access_count DESC, s.create_time DESC " +
            "LIMIT #{limit}")
    List<DocumentShareVO> selectHotShares(@Param("limit") Integer limit);

    /**
     * 搜索分享
     * 
     * @param keyword 关键词
     * @param limit 限制数量
     * @return 分享列表
     */
    @Select("SELECT s.*, d.title as document_title, u.real_name as sharer_name " +
            "FROM document_share s " +
            "LEFT JOIN document d ON s.document_id = d.id " +
            "LEFT JOIN user u ON s.sharer_id = u.id " +
            "WHERE s.deleted = 0 AND s.status = 1 " +
            "AND s.share_type = 1 " +
            "AND (s.title LIKE CONCAT('%', #{keyword}, '%') " +
            "OR s.description LIKE CONCAT('%', #{keyword}, '%') " +
            "OR d.title LIKE CONCAT('%', #{keyword}, '%')) " +
            "ORDER BY s.access_count DESC, s.create_time DESC " +
            "LIMIT #{limit}")
    List<DocumentShareVO> searchShares(@Param("keyword") String keyword,
                                      @Param("limit") Integer limit);

    /**
     * 复制分享
     * 
     * @param sourceShareId 源分享ID
     * @param newTitle 新标题
     * @param sharerId 分享者ID
     * @return 新分享ID
     */
    String copyShare(@Param("sourceShareId") String sourceShareId,
                    @Param("newTitle") String newTitle,
                    @Param("sharerId") String sharerId);

    /**
     * 禁用文档的所有分享
     * 
     * @param documentId 文档ID
     * @return 影响行数
     */
    @Update("UPDATE document_share SET status = 0, update_time = NOW() " +
            "WHERE document_id = #{documentId} AND deleted = 0")
    int disableDocumentShares(@Param("documentId") String documentId);

    /**
     * 获取分享访问记录
     * 
     * @param shareId 分享ID
     * @param limit 限制数量
     * @return 访问记录
     */
    List<Object> selectShareAccessLogs(@Param("shareId") String shareId,
                                      @Param("limit") Integer limit);
}
